package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;

import net.ConnectionHandler;
import net.EncryptedConnectionHandler;
import net.MessageReceivedListener;
import net.StandardConnectionHandler;
import types.Message;
import types.MessageType;

public class Server {
	
	private static int port = 11111;
	public boolean serverStarted = true;
	private ServerSocket serverSocket;
	
	private ArrayList<ConnectionHandler> connectionHandlers = new ArrayList<ConnectionHandler>();
	
	public void start() {
		
		try 
		{
			ServerSocket serverSocket = new ServerSocket(port);

			while(serverStarted) 
			{				
				Socket socket = serverSocket.accept();  	
				
				MessageReceivedListener messageReceivedListener = new MessageReceivedListener() {
					
					@Override
					public void messageReceived(Message message) {
						
						switch(message.getMessageType()) {

							case MESSAGE:
								sendToAll(message.getMessage(), message.getCreator());
								break;
							case DISCONNECT:
								break;
							case LOGIN:
								break;
							case LOGIN_OK:
								break;
							case LOGON_FAILD:
								break;
							case USERNAME_EXISTING:
								break;
						
						}
					}
				};
				
				ConnectionHandler connectionHandler = new EncryptedConnectionHandler(socket, messageReceivedListener, "1234567890qwerty");
				connectionHandlers.add(connectionHandler); 
			}
			
			for(ConnectionHandler connectionHandler : connectionHandlers){
				connectionHandler.closeSocket();
			}
			
		}
		catch (Exception e) {
		}
	}		
	
	private synchronized void sendToAll(String message, String creator) {
		
		for(ConnectionHandler connectionHandler : connectionHandlers) {
			//connectionHandler.writeMessage(message);
			//czemu uzywasz pustej dopisanej przez siebie writeMessage skoro masz sendMessage dzialajaca
			try {
				connectionHandler.sendMessage(new Message(message, new Date(), creator, MessageType.MESSAGE));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}

}

	